package com.weilus;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientProperties;
import org.springframework.data.elasticsearch.core.ReactiveElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;


/**
 * @author 刘太全
 * @program springCloud-k8s
 * @date 2019-07-26 14:48
 **/
@RestController
@Slf4j
public class ArticleController {

    @Autowired
    private ArticleRepository repository;
    @Autowired
    private ReactiveElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private ReactiveElasticsearchRestClientProperties properties;

    /**
     * curl -H "Content-Type: application/json" -X POST  \
     * --data '{"id":1,"title":"中国商人在沙特唐人街开中餐饭店","content":"这是内容。中国商人在沙特唐人街开中餐饭店","author":"admin"}' \
     * http://10.244.1.25:8080/article
     * @return
     */
    @PostMapping("article")
    public Mono<Article> add(@RequestBody Article article){
        return repository.save(article);
    }

    // curl http://10.244.1.203:8080/article?title=唐人街
    @GetMapping("article")
    public Flux<Article> search(Article art){
        NativeSearchQuery query = new NativeSearchQuery(QueryBuilders.matchQuery("title",art.getTitle()));
        return elasticsearchTemplate.search(query,Article.class).map(SearchHit::getContent);
    }

    @GetMapping("properties")
    public Mono<ReactiveElasticsearchRestClientProperties> properties(){
        return Mono.just(properties);
    }

}
